<template>
  
  <div class="main-content order-list-wrapper">
    <div class="filter-box" v-if="props.tableType==1">

      <el-form :inline="true" :model="form">
        <div class="item">
          <el-form-item label="消费时间">
            <el-date-picker
              v-model="form.date"
              type="daterange"
              range-separator="至"
              value-format="YYYY-MM-DD"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              @change="changeDate" />
          </el-form-item>
          <el-form-item label="消费类型">
            <el-select
              v-model="form.packageType"
              placeholder="请选择"
              clearable
            >
              <el-option v-for="item in packageTypes" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="付款方式">
            <el-select
              v-model="form.resourcePackageType"
              placeholder="请选择"
              clearable
            >
              <el-option v-for="item in resourcePackageTypes" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
        </div>
        <div class="item">
          <el-form-item label="产品">
            <el-select
              v-model="form.materialType"
              placeholder="请选择"
              clearable
            >
            <el-option v-for="item in materialTypes" :label="item.label" :value="item.value" :key="item.value" />
            </el-select>
          </el-form-item>
          <el-form-itm>
            <!-- 操作 -->
            <div class="btn-box">
              <el-button
                type="primary"
                @click="searchFn">
                查询
              </el-button>
              <!-- 重置 -->
              <el-button
                type=""
                @click="restFn">
                重置
              </el-button>

            </div>
          </el-form-itm>
        </div>
      </el-form>
    </div>

    <div class="content-box">
      <ct-table :options="tableOptions" :key="tableKey">
        <template v-slot:index="scope">
          <span>{{ scope.row.index }}</span>
        </template>
        <template v-slot:materialType="scope">
          {{ findLabel(materialTypes, scope.row.materialType) }}
        </template>
        <template v-slot:resourcePackageType="scope">
          {{ findLabel(resourcePackageTypes, scope.row.resourcePackageType) }}
        </template>
        <template v-slot:packageType="scope">
          {{ findLabel(packageTypes, scope.row.packageType) }}
        </template>
        <!-- materialTypes -->
        <template v-slot:costTime="scope">
          {{ scope.row.createdAt}}- {{scope.row.costTime}}
        </template>
        <template v-slot:operate="scope">
          <el-text type="primary" @click="toDetail(scope.row)">
            详情
          </el-text>
        </template>
      </ct-table>

      <ct-pagination v-if="props.tableType === '1'" :options="pageOptions" :pageEvent="userPaymentsfn"></ct-pagination>
      <ct-pagination v-else-if="props.tableType === '2'" :options="pageOptions" :pageEvent="debouncedCustomerTransferVoucherfn('TRANSFER')"></ct-pagination>
      <ct-pagination v-else :options="pageOptions" :pageEvent="debouncedCustomerTransferVoucherfn('GIVE')"></ct-pagination>
      
      <div class="totalbox">费用合计：{{ tableOptions.total?tableOptions.total:"0.00" }}</div>
    
    </div>
  </div>
</template>

<script setup>
import { getOrderList, customerTransferVoucher,userPayments } from '@/api/index';
import { useRouter, useRoute } from 'vue-router';
import { ref, reactive, watchEffect, getCurrentInstance, defineProps } from 'vue';
import CtTable from '@/components/CtTable.vue';
import CtPagination from '@/components/Pagination.vue';
import { usePageOptions } from '@/hooks/usePageOptions';

const router = useRouter();
const route = useRoute();
const { proxy } = getCurrentInstance();

const { pageOptions } = usePageOptions();

const props = defineProps({
  thisMonthCost: {
    type: Object,
  },
  tableType: {
    type: String,
    default: '1',
  },
});

let form = ref({
  data:null,
  packageType:null,
  materialType:null,
  resourcePackageType:null,
  resourceStatusOption:null,
  endTime:null,
  limit:null,
  startTime:null,
  page:null,
  userId:null
});

// 消费类型
const packageTypes = ref([
        { label: '全部', value: null }, 
        { label: '包年', value: 0 },
        { label: '包月', value: 1 },
        { label: '按量', value: 2 },
        { label: '包年差额', value: 3 },
        { label: '包月差额', value: 4 },
        { label: '按量差额', value: 5 },
        { label: '包周', value: 6 },
        { label: '包周差额', value: 7 },
        { label: '续年', value: 8 },
        { label: '续月', value: 9 },
        { label: '续周', value: 10 },
        { label: '续年差额', value: 11 },
        { label: '续月差额', value: 12 },
        { label: '续周差额', value: 13 },
        { label: '包天', value: 14 },
        { label: '包小时', value: 15 },
        { label: '续天差额', value: 16 },
        { label: '续小时差额', value: 18 },
        { label: '续天', value: 20 },
        { label: '续小时', value: 21 },
        { label: '包天差额', value: 22 },
        { label: '包小时差额', value: 23 }
      ])

// 消费类型
const materialTypes = ref([
        { label: '全部', value: null },
        { label: '训练环境', value: 0 },
        { label: '训练任务', value: 1 },
        { label: '存储服务', value: 2 },
        { label: '模型服务', value: 3 },
        { label: '训练任务分布式', value: 4 },
        { label: '训练环境分布式', value: 5 },
        { label: 'autoML', value: 6 },
        { label: '标注转化', value: 7 }
      ])

// 付款方式
const resourcePackageTypes = ref([
        { label: '全部', value: null },
        { label: '预付费', value: 0 },
        { label: '后付费', value: 1 }
      ])

// 消费类型
const resourceStatusOptions=ref([
        { label: '资源不足', value: -9 },
        { label: '扩缩容资源不足', value: -6 },
        { label: '扩缩容失败', value: -4 },
        { label: '恢复失败', value: -3 },
        { label: '申请失败', value: -2 },
        { label: '审核不通过', value: -1 },
        { label: '待审核', value: 0 },
        { label: '运行中', value: 1 },
        { label: '扩容待审核', value: 2 },
        { label: '已回收', value: 3 },
        { label: '资源申请中', value: 4 },
        { label: '恢复中', value: 5 },
        { label: '扩容中', value: 6 }
      ])


const searchFn = proxy.$debounce(() => {
  tableOptions.data = [];
  pageOptions.currentPage = 1;
  pageOptions.total = 0;

  userPaymentsfn();
});
function findLabel(types, value) {
    const type = types.find(t => t.value === value);
    return type ? type.label : '未知'; // 如果找不到匹配项，返回'未知'
}

function restFn(){
  form.value={
    data:null,
    packageType:null,
    materialType:null,
    resourcePackageType:null,
    resourceStatusOption:null,
    endTime:null,
    limit:null,
    startTime:null,
    page:null,
    userId:null
  }
  searchFn();
}


function changeDate(value) {
    if (value) {
      form.value.startTime = value[0] + ' 00:00:00';
      form.value.endTime = value[1] + ' 23:59:59';
    } else {
      form.value.startTime = '';
      form.value.endTime = '';
    }

    searchFn();
  }

const tableKey = ref(0);

function toDetail(row) {
  router.push({
    name: 'OrderDetail',
    query: {
      orderId: row.id,
      userId: route.query.id,
    },
  });
}

const orderTablelist = [
  { label: '序号', prop: 'index', width: 80, isCustom: true },
  { label: '账单编号', prop: 'tradeNo' },
  { label: '费用(元)', prop: 'money' },
  { label: '区域', prop: 'domain' },
  { label: '部门/ID', prop: 'depId' },
  { label: '组织/ID', prop: 'orgId' },
  { label: '用户', prop: 'username' },
  { label: '产品', prop: 'materialType' ,isCustom: true},
  { label: '产品/ID', prop: 'renewal' },
  { label: '版本号', prop: 'orderTime' },
  { label: '节点数', prop: 'replicas' },
  { label: '资源配置', prop: 'replicas' ,isCustom: true},
  { label: '消费时间', prop: 'costTime' ,isCustom:true},
  { label: '消费类型', prop: 'packageType',isCustom: true },
  { label: '付费类型', prop: 'resourcePackageType' ,isCustom: true},
];

const suanliorderlist = [
  { label: '序号', prop: 'index', width: 80, isCustom: true },
  { label: '划拨方', prop: 'fromUserNickname' },
  { label: '充值金额（元）', prop: 'userRecharge' },
  { label: '划拨金额（元）', prop: 'voucherMoney' },
  { label: '折扣', prop: 'discountRatio' },
  { label: '当前状态', prop: 'state' },
  { label: '划拨到账时间', prop: 'confirmAt' },
  { label: '备注', prop: 'remark' },
];

const suanligivelist = [
  { label: '序号', prop: 'index', width: 80, isCustom: true },
  { label: '赠送方', prop: 'fromUserNickname' },
  { label: '赠送金额（元）', prop: 'voucherMoney' },
  { label: '当前状态', prop: 'state' },
  { label: '赠送操作时间', prop: 'confirmAt' },
  { label: '赠送原因', prop: 'remark' },
];

let tableOptions = reactive({
  data: [],
  loading: false,
  columns: [],
  total:""
});


// 获取账单列表信息
function userPaymentsfn(){
  tableOptions.loading = true

  const { currentPage , pageSize } = pageOptions;
  console.log(route.query.id)
  userPayments({
    packageType: form.value.packageType,
    materialType: form.value.materialType,
    resourcePackageType: form.value.resourcePackageType,
    resourceStatusOption: form.value.resourceStatusOption,
    endTime: form.value.endTime,
    limit: pageSize,
    startTime: form.value.startTime,
    page: currentPage,
    userId: parseInt(route.query.id)
  }).then(res=>{
    const { content, totalElements,data } = res.data;
      if (content.length) {
        for (let i = 0; i < content.length; i++) {
          content[i].index = proxy.$handleIndex(i, pageOptions);
        }
      }
      tableOptions.data = content;
      tableOptions.data = content;
      tableOptions.total = data
      tableOptions.loading = false;
    pageOptions.total = totalElements;
  })    
  .catch(() => {
      tableOptions.loading = false;
  });
}

function getListData() {
  tableOptions.loading = true;
  const { currentPage, pageSize } = pageOptions;

  getOrderList({
    page: currentPage,
    pageSize,
    userId: route.query.id,
  })
    .then((res) => {
      const { content, totalElements } = res.data;
      if (content.length) {
        for (let i = 0; i < content.length; i++) {
          content[i].index = proxy.$handleIndex(i, pageOptions);
        }
      }
      tableOptions.data = content;
      tableOptions.loading = false;
      pageOptions.total = totalElements;
    })
    .catch(() => {
      tableOptions.loading = false;
    });
}
import { debounce } from 'lodash';

const debouncedCustomerTransferVoucherfn = debounce((params) => {
  tableOptions.loading = true;
  const { currentPage, pageSize } = pageOptions;
  console.log(params);
  customerTransferVoucher({
    page: currentPage,
    pageSize,
    userId: route.query.id,
    type: params,
  })
  .then((res) => {
    tableOptions.columns = params === 'TRANSFER' ? suanliorderlist : suanligivelist;
    const { content, totalElements } = res.data;
    if (content.length) {
      for (let i = 0; i < content.length; i++) {
        content[i].index = proxy.$handleIndex(i, pageOptions);
      }
    }
    tableOptions.data = content;
    tableOptions.total = tableOptions.data.length > 0 ? tableOptions.data[0].voucherTotal : "0.00";
    tableOptions.loading = false;
    pageOptions.total = totalElements;
  })
  .catch(() => {
    tableOptions.loading = false;
  });
}, 300); // 300 ms 延迟时间

function changeStatus(tableType) {
  tableOptions.data = [];
  tableOptions.loading = false;
  if (tableType === '1') {
    userPaymentsfn();
    tableOptions.columns = orderTablelist;
  } else if (tableType === '2') {
    tableOptions.columns = suanliorderlist;
    // debouncedCustomerTransferVoucherfn('TRANSFER');
  } else if (tableType === '3') {
    console.log(3)
    tableOptions.columns = suanligivelist;
    // debouncedCustomerTransferVoucherfn('GIVE');
  }
  tableKey.value = tableType;
}

// watchEffect(() => {
//   chengeStatus(props.tableType);
// });

watch(() => props.tableType, (newType, oldType) => {
  // 避免初始化时就调用，除非确实需要立即执行
  if (newType !== oldType) {
    changeStatus(newType);
  }
}, { immediate: true });



</script>

<style lang="scss" scoped>
.order-list-wrapper {
  position: relative;
  height: 400px;
  .total-amount {
    position: absolute;
    bottom: 30px;
    color: var(--color-font-color);
    .title {
      font-size: 14px;
      float: left;
    }
    .amount {
      float: left;
      margin-left: 10px;
    }
  }
}
.btn-box{
  margin-top: -20px;
}
</style>
